package com.tien.action;

/**
 * @author Tien  E-mail:g.tianxin@gmail.com
 * @version Time：2011-8-18 下午10:59:58
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tien.model.Article;
import com.tien.model.Classify;
import com.tien.model.Content;
import com.tien.model.Employee;
import com.tien.utils.EMF;

/**
 * @author xt40919
 * @version Create Time：Aug 16, 2011 10:45:23 AM
 */

public class ArticleAction extends HttpServlet {

	/**
	* 
	*/
	private static final long serialVersionUID = -6104772463727039659L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		// String userId = req.getParameter("userId");
		String operate = req.getParameter("operate");
		String start = req.getParameter("start");
		String limit = req.getParameter("limit");
		String result = "/blog.jsp";
		if (null == operate)
			operate = "find_articles";
		if (null == start || "".equals(start))
			start = "0";
		if (null == limit || "".equals(limit))
			limit = "20";
		Employee employee = (Employee) req.getSession()
				.getAttribute("employee");
		System.out.println("userId:" + employee.getId());
		Article article = null;
		PersistenceManager pm = EMF.get().getPersistenceManager();
		// Transaction tx = pm.currentTransaction();
		try {
			// tx.begin();

			// to update article jsp
			if (null != operate && "to_update_article".equals(operate)) {
				article = findArticle(pm, req, resp);
				req.getSession().setAttribute("updateArticleState", "");
				req.setAttribute("article", article);
				result = "/updateArticle.jsp";
			}
			// update article
			if (null != operate && "update_article".equals(operate)) {
				article = updateArticle(pm, req, resp);
				req.getSession().setAttribute("article", article);
				req.getSession().setAttribute("updateArticleState", "修改成功");
				result = "/updateArticle.jsp";
				sleeeping(2000);
				resp.sendRedirect(result);
				return;
			}
			// save article
			if (null != operate && "save_article".equals(operate)) {
				saveArticle(pm, req, resp, employee);
				result = "/blog?operate=find_articles";
				sleeeping(2000);
				resp.sendRedirect(result);
				return;
			}
			// find article detail
			if (null != operate && "delete_article".equals(operate)) {
				deleteArticle(pm, req, resp);
				result = "/blog?operate=find_articles";
				sleeeping(2000);
				resp.sendRedirect(result);
				return;
			}
			// find article detail
			if (null != operate && "find_article".equals(operate)) {
				article = findArticle(pm, req, resp);
				req.setAttribute("article", article);
				sleeeping(2000);
				result = "/article.jsp";
				if (null != req.getParameter("result")) {
					result = req.getParameter("result");
				}
			}

			// find articles by userid
			if (null != operate && "find_articles".equals(operate)) {
				findArticles(pm, req, resp, start, limit, employee);
			}

			RequestDispatcher dispatcher = req.getRequestDispatcher(result);
			try {
				dispatcher.forward(req, resp);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			/*
			 * resp.sendRedirect(result);
			 */
		} finally {
			// if (tx.isActive()) {
			// tx.rollback();
			// }
			pm.close();
		}
	}

	private void saveArticle(PersistenceManager pm, HttpServletRequest req,
			HttpServletResponse resp, Employee employee) {
		Article article = new Article(employee.getId(),
				req.getParameter("classify"), req.getParameter("title"), 0,
				new Date());
		Content content = new Content();
		content.setContent(req.getParameter("content"));
		article.setContent(content);
		article = pm.makePersistent(article);
		try {
			// after 3 seconds redirect
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void deleteArticle(PersistenceManager pm, HttpServletRequest req,
			HttpServletResponse resp) {
		Article article = findArticle(pm, req, resp);
		pm.deletePersistent(article);
	}

	private Article updateArticle(PersistenceManager pm,
			HttpServletRequest req, HttpServletResponse resp) {
		Article article = findArticle(pm, req, resp);
		article.setTitle(req.getParameter("title"));
		Content content = new Content();
		content.setContent(req.getParameter("content"));
		article.setContent(content);
		String classify = req.getParameter("classify");
		if (null != classify && !"".equals(classify))
			article.setClassify(classify);
		pm.makePersistent(article);
		return article;
	}

	private Article findArticle(PersistenceManager pm, HttpServletRequest req,
			HttpServletResponse resp) {
		Article article = null;
		String articleId = req.getParameter("articleId");
		Query queryArticle = pm.newQuery(Article.class);
		queryArticle.setFilter("id == articleIdParam");
		queryArticle.declareParameters("String articleIdParam");
		article = ((List<Article>) queryArticle.execute(Long
				.parseLong(articleId))).get(0);
		article.setClickNum(article.getClickNum() + 1);
		article.setCommentsCount(article.getComments().size());
		article = pm.makePersistent(article);
		return article;
	}

	private List<Article> findArticles(PersistenceManager pm,
			HttpServletRequest req, HttpServletResponse resp, String start,
			String limit, Employee employee) {
		List<Article> articles = new ArrayList<Article>();
		Query queryArticle = pm.newQuery(Article.class);
		queryArticle.setFilter("employeeId == employeeIdParam");
		queryArticle.setOrdering("publisherDate desc");
		queryArticle.declareParameters("String employeeIdParam");
		queryArticle.setRange(Integer.parseInt(start), Integer.parseInt(start)
				+ Integer.parseInt(limit));
		try {
			articles = (List<Article>) queryArticle.execute(employee.getId());
			for (Article a : articles) {
				System.out.println("comment count:" + a.getCommentsCount());
			}
		} finally {
			queryArticle.closeAll();
		}
		req.setAttribute("articles", articles);
		return articles;
	}

	private void sleeeping(int sleepingTimsMs) {
		try {
			// after 3 seconds redirect
			Thread.sleep(sleepingTimsMs);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
